#!/usr/bin/env bash
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
export RESOURCES_DIR="$DIR/Resources"
export CHURCH_PRESENTATION_ASSETS="$DIR/Resources/assets"

# Configure macOS environment paths (Bundled tools + Homebrew Apple Silicon and Intel)
export PATH="$DIR/Resources/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/local/sbin:$PATH"

if [ -d "/opt/homebrew/opt/qt6" ]; then
    export QT_DIR="/opt/homebrew/opt/qt6"
    export QT_PLUGIN_PATH="$QT_DIR/share/qt/plugins"
    export QML2_IMPORT_PATH="$QT_DIR/share/qt/qml"
elif [ -d "/usr/local/opt/qt6" ]; then
    export QT_DIR="/usr/local/opt/qt6"
    export QT_PLUGIN_PATH="$QT_DIR/share/qt/plugins"
    export QML2_IMPORT_PATH="$QT_DIR/share/qt/qml"
fi

# 1. Configure bundled CA certificates for HTTPS across all embedded tools & Qt
if [ -f "$DIR/Resources/assets/certs/cacert.pem" ]; then
    export SSL_CERT_FILE="${SSL_CERT_FILE:-$DIR/Resources/assets/certs/cacert.pem}"
    export REQUESTS_CA_BUNDLE="${REQUESTS_CA_BUNDLE:-$DIR/Resources/assets/certs/cacert.pem}"
    export CURL_CA_BUNDLE="${CURL_CA_BUNDLE:-$DIR/Resources/assets/certs/cacert.pem}"
fi

# 2. Execute pre-compiled Mach-O binary if bundled
if [ -x "$DIR/MacOS/church-presentation-bin" ]; then
    exec "$DIR/MacOS/church-presentation-bin" "$@"
fi

# 2. Execute system installed binary if available
if command -v church-presentation >/dev/null 2>&1; then
    exec church-presentation "$@"
fi

# 3. Informative native macOS dialog
if command -v osascript >/dev/null 2>&1; then
    osascript -e 'display alert "Ukweli Church & Meetings Presentation Studio" message "To run on macOS, ensure Qt 6 is available via Homebrew (for source/non-standalone builds):

brew install qt6 poppler libreoffice ffmpeg

Bundled stream extractor, QuickJS runtime, and CA certificates are included in Resources.
Visit https://ukwelicode.com/church-presentation for complete documentation." as informational buttons {"Open Website", "OK"} default button "OK"'
fi
